<template>
  <div class="activity-list">
    <h1>我的活动</h1>

    <!-- 搜索筛选 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="活动类型">
          <el-select v-model="searchForm.type" placeholder="请选择活动类型" clearable>
            <el-option
              v-for="item in activityTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.mactivityName" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="活动地点">
          <el-input v-model="searchForm.address" placeholder="请输入活动地点" clearable />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.state" placeholder="请选择活动状态" clearable>
            <el-option label="已报名" value="已报名"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="未答完" value="未答完"></el-option>
            <el-option label="已答完" value="已答完"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 活动列表 -->
    <el-card class="services-table-card">
      <template #header>
        <div class="card-header">
          <span>我的参与记录</span>
        </div>
      </template>

      <el-table :data="paginatedActivities" style="width: 100%" >
        <el-table-column prop="mactivityId" label="活动ID" />
        <el-table-column prop="mactivityName" label="活动名称" />
        <el-table-column prop="address" label="活动地点" />
        <el-table-column prop="type" label="类型" >
          <template #default="scope">
            <span v-if="scope.row.type == 0">资源回收</span>
            <span v-else-if="scope.row.type == 1">护水行动</span>
            <span v-else-if="scope.row.type == 2">公益之星</span>
          </template>
        </el-table-column>
        <el-table-column prop="activityTime" label="活动时间" />
        <el-table-column prop="state" label="状态" width="100">
          <template #default="scope">
            <!-- <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag> -->
             <span v-if="scope.row.state == 0">已报名</span>
             <span v-else-if="scope.row.state == 1">已完成</span>
             <span v-else-if="scope.row.state == 2">未答完</span>  
             <span v-else-if="scope.row.state == 3">已答完</span>  
          </template>
        </el-table-column>
        <!-- <el-table-column prop="time" label="活动时间" />
        <el-table-column prop="registrationDate" label="报名日期" /> -->
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="viewDetails(scope.row)">查看详情</el-button>
            <el-button v-show="showButton(scope.row)" size="small" @click="finishActivity(scope.row)">完成活动</el-button>
            <el-button v-show="showButton1(scope.row)" size="small" @click="finishActivity(scope.row)">完成答题</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalActivities"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="活动详情"
      width="500px"
    >
      <p><strong>活动ID:</strong> {{ selectedActivityDetails?.mactivityId }}</p>
      <p><strong>活动名称:</strong> {{ selectedActivityDetails?.mactivityName }}</p>
      <p><strong>类型:</strong>
        <span v-if="selectedActivityDetails?.type == 0">资源回收</span>
        <span v-else-if="selectedActivityDetails?.type == 1">护水行动</span>
        <span v-else-if="selectedActivityDetails?.type == 2">公益之星</span>  
      </p>
      <p><strong>状态:</strong> 
        <span v-if="selectedActivityDetails?.state == 0">已报名</span>
        <span v-else-if="selectedActivityDetails?.state == 1">已完成</span>
        <span v-else-if="selectedActivityDetails?.state == 2">未答完</span>  
        <span v-else-if="selectedActivityDetails?.state == 3">已答完</span>  
      </p>
      <p><strong>活动时间:</strong> {{ selectedActivityDetails?.activityTime }}</p>
      <p><strong>地点:</strong> {{ selectedActivityDetails?.address }}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {
  Delete,
  Pouring,
  Star,
  Calendar,
  Location,
  User
} from '@element-plus/icons-vue'

const router = useRouter()

// 获取当前用户ID
const getCurrentUserId = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.id || userInfo.userId
}

// 活动类型（用于搜索筛选）
const activityTypes = ref([
  { label: '资源回收', value: '0' },
  { label: '护水行动', value: '1' },
  { label: '公益之星', value: '2' }
])

// 搜索表单
const searchForm = ref({
  type: null,
  mactivityName:'',
  address : '',
  state: null
})

// 活动数据（从后端获取）
const allActivities = ref([])

// 直接使用后端数据，不需要前端筛选
const activities = computed(() => allActivities.value)

const currentPage = ref(1)
const pageSize = ref(10)

const totalActivities = computed(() => activities.value?.length || 0)

const paginatedActivities = computed(() => {
  if (!activities.value || !Array.isArray(activities.value)) {
    return []
  }
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return activities.value.slice(start, end)
})

const detailsDialogVisible = ref(false)
const selectedActivityDetails = ref(null)

const getStatusTagType = (state) => {
  switch (state) {
    case '已报名':
      return 'info'
    case '已完成':
      return 'success'
    case '进行中':
      return 'warning'
    case '已答完':
      return 'success'
    default:
      return ''
  }
}

const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置回第一页
  console.log('执行搜索，搜索条件:', searchForm.value)
  getActivityList() // 直接调用后端搜索接口
}

const resetSearch = () => {
  searchForm.value = {
    type: null,
    mactivityName: '',
    address: '',
    state: null
  }
  currentPage.value = 1
  console.log('重置搜索条件')
  getActivityList() // 重置时重新获取数据
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 页面大小改变时不需要重置currentPage，分页组件会自动处理
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const viewDetails = (allActivities) => {
  selectedActivityDetails.value = allActivities
  detailsDialogVisible.value = true
}

const getActivityList = async () => {
  try {
    // 获取当前用户ID
    // const userId = getCurrentUserId()
    // if (!userId) {
    //   ElMessage.warning('请先登录')
    //   return
    // }
    const userId = 1
    let fd = new FormData()
    fd.append('userId', userId)
    
    if(searchForm.value.type != null){
      fd.append('type', searchForm.value.type)
    }
    fd.append('mactivityName', searchForm.value.mactivityName)
    fd.append('address', searchForm.value.address)
    
    if(searchForm.value.state != null){
      const statusMap = {
        '已报名': 0,
        '已完成': 1,
        '未答完': 2,
        '已答完': 3
      }
      const targetState = statusMap[searchForm.value.state]
      if (targetState !== undefined) {
        fd.append('state', targetState)
      }
    }

    console.log('发送的搜索参数:', {
      userId,
      type: searchForm.value.type,
      mactivityName: searchForm.value.mactivityName,
      address: searchForm.value.address,
      state: searchForm.value.state
    })

    // 从后端获取用户的活动列表
    const response = await axios.post('http://localhost:9000/myactivity/list', fd)
    
    if (response.data.isOk) {
      if (response.data.list && Array.isArray(response.data.list)) {
        allActivities.value = response.data.list
        ElMessage.success(`成功加载 ${response.data.list.length} 条活动记录`)
      } else {
        allActivities.value = []
        ElMessage.info('您还没有参与任何活动')
      }
    } else {
      ElMessage.error('获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('网络错误，获取活动列表失败')
  }
}

const showButton = (allActivities) =>{
  if(allActivities.state == 0){
    return true
  }else{
    return false
  }
}

const showButton1 = (allActivities) => {
  if(allActivities.state == 2){
    return true
  }else{
    return false
  }
}

const finishActivity = async (allActivities) =>{
  if(showButton(allActivities) == true){
    allActivities.state = 1
    await updateState(allActivities)
  }else if(showButton1(allActivities) == true){
    allActivities.state = 3
    await updateState(allActivities)
  }
}

const updateState = async (allActivities) =>{
  try {
    let fd = new FormData()
    fd.append('mactivityId', allActivities.mactivityId)
    fd.append('state', allActivities.state)
    fd.append('activityTime', allActivities.activityTime)
    fd.append('address', allActivities.address)
    fd.append('mactivityName', allActivities.mactivityName)
    fd.append('userId', allActivities.userId)
    
    const response = await axios.post('http://localhost:9000/myactivity/updateState', fd)
    if(response.data.isOk){
      ElMessage.success('状态更新成功')
      getActivityList()
    }else{
      ElMessage.error('状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('网络错误，状态更新失败')
  }
}


onMounted(async () => {
  getActivityList()
})
</script>

<style lang="scss" scoped>
.activity-list {
  padding: 20px;
  background-color: #f0f2f5;

  h1 {
    color: #303133;
    margin-bottom: 20px;
    text-align: center;
  }

  .search-bar {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .services-table-card {
    margin-top: 20px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 15px;
  }

  .pagination-block {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 